// 帖子和二手可以共用这个评论
import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const CollectSchema = new mongoose.Schema({
    desc: String,
    postId: String,
    url: String, // 跳转地址
    creatorId: String,
    creator: Object,
    createTime: Number,
});

CollectSchema.methods.saveCollect = function (collect, cb) {
    collect.createTime = moment().unix();
    this.model('collect').insertMany([collect], cb);
};

CollectSchema.methods.getCollects = function (query, cb) {
    const { current, pageSize, ...leftQuery } = query;
    const collectModel = this.model('collect');
    if (leftQuery.createTime) {
        leftQuery.createTime = { $lt: leftQuery.createTime }
    }
    collectModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        collectModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, collects) => cb(err, collects, count, hasMore));
    });
};

CollectSchema.methods.getAllCollects = function (query, cb) {
    this.model('collect').find(query, cb);
};

CollectSchema.methods.getCollect = function (query, cb) {
    this.model('collect').findOne(query, cb);
};

CollectSchema.methods.updateCollect = function (collect, cb) {
    const _id = collect._id;
    delete collect._id;
    this.model('collect').findOneAndUpdate({ _id }, { $set: collect }, cb);
};

CollectSchema.methods.removeCollects = function (collectIds, cb) {
    this.model('collect').remove({ _id: { $in: collectIds } }, cb);
};

export default db.model('collect', CollectSchema);